﻿CREATE PROCEDURE dbo.sched_Job
	@JobName nvarchar(512),
	@Command nvarchar(4000),
	@Seconds int = 60,
	@Category nvarchar(512) = 'Dimok Jobs',
	@DBName nvarchar(256) = null
AS

BEGIN TRANSACTION            
  DECLARE @JobID BINARY(16)  
  DECLARE @ReturnCode INT    
  SELECT @ReturnCode = 0     
IF (SELECT COUNT(*) FROM msdb.dbo.syscategories WHERE name = @Category) < 1 
  EXECUTE msdb.dbo.sp_add_category @name = @Category
  -- Delete the job with the same name (if it exists)
SELECT @JobID = job_id FROM msdb.dbo.sysjobs WHERE (name = @JobName)       
IF (@JobID IS NOT NULL) BEGIN -- Delete the [local] job 
  EXECUTE msdb.dbo.sp_delete_job @job_name = @JobName 
  SELECT @JobID = NULL
END 
-- Set start datetime
DECLARE @StartDate sysname,@StartTime sysname,@Now datetime
SET @Now = DATEADD(ss,@Seconds,getdate())
SELECT @StartDate = CONVERT(varchar,@Now,112),@StartTime = REPLACE(CONVERT(varchar,@Now,108),':','')

IF @DBName IS NULL SET @DBName = DB_NAME()

BEGIN 
  -- Add the job
  EXECUTE @ReturnCode = msdb.dbo.sp_add_job @job_id = @JobID OUTPUT , @job_name = @JobName, @owner_login_name = N'AFC-HOME\SQLServer', @description = N'', @category_name = @Category, @enabled = 1, @notify_level_email = 2, @notify_level_page = 0, @notify_level_netsend = 0, @notify_level_eventlog = 2, @delete_level= 1, @notify_email_operator_name = N'Dimok'
  IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback 
  -- Add the job steps
  EXECUTE @ReturnCode = msdb.dbo.sp_add_jobstep @job_id = @JobID, @step_id = 1, @step_name = N'Step', @command = @Command, @database_name = @DBName, @server = N'', @database_user_name = N'', @subsystem = N'TSQL', @cmdexec_success_code = 0, @flags = 4, @retry_attempts = 4, @retry_interval = 15, @output_file_name = N'', @on_success_step_id = 0, @on_success_action = 1, @on_fail_step_id = 0, @on_fail_action = 2
  IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback 
  EXECUTE @ReturnCode = msdb.dbo.sp_update_job @job_id = @JobID, @start_step_id = 1 
  IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback 
  -- Add the job schedules
  EXECUTE @ReturnCode = msdb.dbo.sp_add_jobschedule @job_id = @JobID, @name = N'RunAt', @enabled = 1, @freq_type = 1, @active_start_date = @StartDate, @active_start_time = @StartTime
  IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback 
  -- Add the Target Servers
  EXECUTE @ReturnCode = msdb.dbo.sp_add_jobserver @job_id = @JobID, @server_name = N'(local)' 
  IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback 

END
COMMIT TRANSACTION          

--EXEC Model_Security.dbo.sh_Jobs_RunByCategory @Category

GOTO   EndSave              
QuitWithRollback:
  IF (@@TRANCOUNT > 0) ROLLBACK TRANSACTION 
EndSave: 




